package com.leyou.auth.web;

import com.leyou.auth.service.AuthService;
import com.leyou.common.auth.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     * @param username  用户名称
     * @param password  用户密码
     * @return      无
     */
    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password, HttpServletResponse response){
        authService.login(username, password, response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 校验token
     * @param request  请求对象，里面有cookie
     * @return      返回用户信息
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(HttpServletRequest request, HttpServletResponse response){
        UserInfo userInfo = authService.verify(request, response);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 用户退出功能
     * @param request       请求对象，用于获取cookie
     * @param response      响应对象，用于设置cookie的时间为0【相当于删除了cookie】
     * @return  无
     */
    @PostMapping("/logout")
    public ResponseEntity<Void> logout(HttpServletRequest request, HttpServletResponse response){
        authService.logout(request,response);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 微服务之间的授权
     * @param id        微服务的id
     * @param secret    微服务的密码
     * @return          返回授权后的JWT
     */
    @GetMapping("/authorization ")
    public ResponseEntity<String> authorization(@RequestParam("id") Long id, @RequestParam("secret") String secret){
        return ResponseEntity.ok(authService.authorization(id, secret));
    }
}
